package com.zhixin.fans.ks.api.parser;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.androidnetworking.interfaces.Parser;
import com.blankj.utilcode.util.Utils;
import com.google.gson.TypeAdapter;
import com.zhixin.fans.ks.CoupleApp;

import java.io.IOException;

import okhttp3.ResponseBody;

public class DefaultResponseBodyParser<T> implements Parser<ResponseBody, T> {

    private final TypeAdapter<T> adapter;

    DefaultResponseBodyParser(TypeAdapter<T> adapter) {
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        DefaultResponse response = JSON.parseObject(value.string(), DefaultResponse.class);
        if (response.isSusseccful()) {
            try {
                return adapter.fromJson(response.getRespData());
            } finally {
                value.close();
            }
        } else {
            if (response.getRespCode().equals("F2")) {
                ((CoupleApp) Utils.getApp()).getCoupleAppComponent().getUserInfoManager().logout();
                ((CoupleApp) Utils.getApp()).getCoupleAppComponent().getUserInfoManager().update();
            }
            throw new IOException(TextUtils.isEmpty(response.getRespData()) ? value.string() : response.getRespData());
        }
    }




}
